﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Data.SqlClient;
using System.Data;
using TSL_Tools.SqlTools;
using ReportingEngine;
using System.IO;
using Xceed.Wpf.Toolkit.PropertyGrid;
using System.Diagnostics;

namespace VSLT_Reporting
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        #region Treeview handlers ------------------------------------------------------------------
        private void BuildInitialLoadTestTreeViewItems(int runId)
        {
            // Create root node for load test items
            TreeViewItem item = new TreeViewItem();
            item.Header = "LoadTest";          
            item.Tag = new PerfmonTreeViewItemId(0, 0, true);

            string sqlCmd = String.Format("SELECT CounterCategoryId, CategoryName FROM LoadTestPerformanceCounterCategory WHERE LoadTestRunId = {0} AND CategoryName LIKE 'LoadTest:%'", runId);
            string sqlConn = Properties.Settings.Default.sqlConn;
            DataTable _table;
            TimeSpan ts = tts.ExecuteReaderTable(sqlCmd, out _table);

            for (int x = 0; x < _table.Rows.Count; x++)
            {
                TreeViewItem subItem = new TreeViewItem();
                subItem.Header = _table.Rows[x][1].ToString();
                subItem.Tag = new PerfmonTreeViewItemId((int)_table.Rows[x][0], 1, true);
                // Add a dummy item to make the node expandable
                TreeViewItem tempItem = new TreeViewItem();
                tempItem.Header = "*";
                subItem.Items.Add(tempItem);
                item.Items.Add(subItem);
            }
            tvPerfmonCounters.Items.Add(item);
        }

        private void BuildInitialComputerTreeViewItems(int runId)
        {
            // Create root node for load test items
            TreeViewItem item = new TreeViewItem();
            item.Header = "Computers";
            item.Tag = new PerfmonTreeViewItemId(0, -1, false);

            string sqlCmd = String.Format("SELECT DISTINCT MachineName FROM LoadTestPerformanceCounterCategory WHERE LoadTestRunId = {0}", runId);
            string sqlConn = Properties.Settings.Default.sqlConn;
            DataTable _table;
            TimeSpan ts = tts.ExecuteReaderTable(sqlCmd, out _table);
            
            // Clear the Perfmon Export machine list as we will populate it at the same time we get the machines for the treeview
            //cbPalMachine.Items.Clear();
            
            for (int x = 0; x < _table.Rows.Count; x++)
            {
                // While we are here, populate the dropdown of machines for Perfmon Export
                //cbPalMachineName.Items.Add(_table.Rows[x][0].ToString());
                
                TreeViewItem subItem = new TreeViewItem();
                subItem.Header = _table.Rows[x][0].ToString();
                subItem.Tag = new PerfmonTreeViewItemId(0, 0, false);
                // Add a dummy item to make the node expandable
                TreeViewItem tempItem = new TreeViewItem();
                tempItem.Header = "*";
                subItem.Items.Add(tempItem);
                item.Items.Add(subItem);

            }
            tvPerfmonCounters.Items.Add(item);
            
        }

        private void PerfmonNodeExpandedEventHndler(RoutedEventArgs e)
        {
            TreeViewItem item = (TreeViewItem)e.OriginalSource;
            PerfmonTreeViewItemId itemInfo = (PerfmonTreeViewItemId)item.Tag;
            if (itemInfo.isLoadTestItem)
                HandleLoadTestNodeExpanded(item);
            else
                HandleComputerNodeExpanded(item);
        }

        private void HandleLoadTestNodeExpanded(TreeViewItem item)
        {
            PerfmonTreeViewItemId itemInfo = (PerfmonTreeViewItemId)item.Tag;
            string sqlCmd = "";

            switch (itemInfo.itemLevel)
            {
                case 1:
                    sqlCmd = String.Format("SELECT CounterId, CounterName FROM dbo.LoadTestPerformanceCounter WHERE " +
                        "LoadTestRunId = {0} AND CounterCategoryId = {1} ORDER BY CounterName ASC", currentlyHighlightedRunId, itemInfo.itemId);
                    break;
                case 2:
                    sqlCmd = String.Format("SELECT InstanceId, InstanceName FROM dbo.LoadTestPerformanceCounterInstance WHERE " +
                        "LoadTestRunId = {0} AND CounterID = {1} ORDER BY InstanceName ASC", currentlyHighlightedRunId, itemInfo.itemId);
                    break;
                default:
                    return;
            }
            Clipboard.SetText(sqlCmd);
            ReadAndSetSubNode(ref item, sqlCmd, itemInfo.itemLevel + 1, itemInfo.isLoadTestItem);
        }

        private void HandleComputerNodeExpanded(TreeViewItem item)
        {
            PerfmonTreeViewItemId itemInfo = (PerfmonTreeViewItemId)item.Tag;
            string sqlCmd = "";

            switch (itemInfo.itemLevel)
            {
                case 0:
                    sqlCmd = String.Format("SELECT CounterCategoryId, CategoryName FROM LoadTestPerformanceCounterCategory WHERE " +
                        "LoadTestRunId = {0} AND MachineName = '{1}' ORDER BY CategoryName ASC", currentlyHighlightedRunId, item.Header);
                    break;
                case 1:
                    sqlCmd = String.Format("SELECT CounterId, CounterName FROM dbo.LoadTestPerformanceCounter WHERE " +
                        "LoadTestRunId = {0} AND CounterCategoryId = {1} ORDER BY CounterName ASC", currentlyHighlightedRunId, itemInfo.itemId);
                    break;
                case 2:
                    sqlCmd = String.Format("SELECT InstanceId, InstanceName FROM dbo.LoadTestPerformanceCounterInstance WHERE " +
                        "LoadTestRunId = {0} AND CounterID = {1} ORDER BY InstanceName ASC", currentlyHighlightedRunId, itemInfo.itemId);
                    break;
                default:
                    return;
            }
            Clipboard.SetText(sqlCmd);
            ReadAndSetSubNode(ref item, sqlCmd, itemInfo.itemLevel + 1, itemInfo.isLoadTestItem);
        }

        private void ReadAndSetSubNode(ref TreeViewItem item, string sqlCmd, int itemLevel, bool loadTestItem)
        {

            if(itemLevel > 0)
                item.Items.Clear();
            string sqlConn = Properties.Settings.Default.sqlConn;
            DataTable _table;
            TimeSpan ts = tts.ExecuteReaderTable(sqlCmd, out _table);
            
            for (int x = 0; x < _table.Rows.Count; x++)
            {
                TreeViewItem subItem = new TreeViewItem();
                subItem.Header = _table.Rows[x][1].ToString();
                subItem.Tag = new PerfmonTreeViewItemId((int)_table.Rows[x][0], itemLevel, loadTestItem);

                if (itemLevel < 3)
                {
                    // Add a dummy item to make the node expandable
                    TreeViewItem tempItem = new TreeViewItem();
                    tempItem.Header = "*";
                    subItem.Items.Add(tempItem);
                }
                item.Items.Add(subItem);
            }
        }

        private void HandleNodeItemSelected(RoutedEventArgs e)
        {
            TreeViewItem item = (TreeViewItem)e.OriginalSource;
            PerfmonTreeViewItemId itemId = item.Tag as PerfmonTreeViewItemId;

            //TreeViewItem parentItem = (TreeViewItem)item.Parent;
            string str = String.Format("SELECTED: Level {0} - Item {1}", itemId.itemLevel, item.Header);
            tsslMessage.Content = str;
        }
        #endregion

        private void getPerfmonCountsForRun()
        {
            string sqlConn = Properties.Settings.Default.sqlConn;
            string sqlCmd = String.Format(TSL_ReportingEngine.Sql_GETPERFMONCOUNTSFORRUN, currentlyHighlightedRunId);
            DataTable _table;
            TimeSpan ts = tts.ExecuteReaderTable(sqlCmd, out _table);

            rtbResults.Document = CreateXamlTableFromDataTable("Perfmon Counts for the run", _table);
        }

        private void LoadPerfmonCounters()
        {

        }
    }

    public class PerfmonTreeViewItemId
    {
        public PerfmonTreeViewItemId(int id, int level, bool loadTestItem)
        {
            itemId = id;
            itemLevel = level;
            isLoadTestItem = loadTestItem;
        }

        public int itemId { get; set; }

        public int itemLevel { get; set; }

        public bool isLoadTestItem { get; set; }
    }

}



